﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Clients;
using B.S.DataBase.MyProject.Domain.OutboundShipments;
using B.S.DataBase.MyProject.Domain.Sales;
using B.S.DataBase.MyProject.Domain.WhereHorse;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.PurchaseInStroeCommand;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.PurchaseInStroeCommandHandler
{
    public class AddPurchaseInStoreCommandHandler : IRequestHandler<AddPurchaseInStoreCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<PurchaseInRepository> purchaseInBiz;
        private readonly IBaseRepository<OrderMaterials> materialBiz;

        public AddPurchaseInStoreCommandHandler(IMapper mapper, IBaseRepository<PurchaseInRepository> purchaseInBiz, IBaseRepository<OrderMaterials> materialBiz)
        {
            this.mapper = mapper;
            this.purchaseInBiz = purchaseInBiz;
            this.materialBiz = materialBiz;
        }

        public Task<APIResult<object>> Handle(AddPurchaseInStoreCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var entity = mapper.Map<PurchaseInRepository>(request);
            entity.Id = Guid.NewGuid();
            int add1 = purchaseInBiz.Add(entity).Result;
            if (add1 > 0)
            {
                request.OrderMaterials.ForEach(c =>
                {
                    c.SaleCode = entity.Id;
                });
                int add2 = materialBiz.AddRanges(request.OrderMaterials).Result;
                if (add2 > 0)
                {
                    result.Code = APIEnum.添加成功;
                    result.Msg = APIEnum.添加成功.ToString();
                }
                else
                {
                    result.Code = APIEnum.添加失败;
                    result.Msg = APIEnum.添加失败.ToString();
                }
            }
            else
            {
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
            }
            return Task.FromResult(result);
        }
    }
}
